﻿using UnityEngine;
using System.Collections;
using System.Linq;

public class WeaponAtlasController : MonoBehaviour
{
    static string prefabPath = "Prefab/Controllers/WeaponController";
    static WeaponAtlasController _instance = null;
    
    UISprite[] m_AtlasContainer = new UISprite[(int)WeaponAtlas.max];
	
    public static  WeaponAtlasController Instance
    {
        get {
            if (_instance == null)
                Create();            
            return _instance; }
        set { _instance = value; }
    }

    static void Create()
    {
        GameObject preFab = ResourceLoader.Load(prefabPath) as GameObject;
        GameObject temp = Instantiate(preFab) as GameObject;
        DontDestroyOnLoad(temp);
		_instance = temp.GetComponent("WeaponAtlasController") as WeaponAtlasController;
    }

    void Awake()
    {
        int max = (int)WeaponAtlas.max;
        for (int i = 0; i < max ; i++) 
        {
            m_AtlasContainer[i] = transform.Find(((WeaponAtlas)i).ToString()).GetComponent("UISprite") as UISprite;
        }
    }

    public static void SetWeaponSprite(UISprite sprite, Item item)
    {
        string modelName = TextController.GetItemDefine(item);

        SetWeaponSprite(sprite, modelName);
    }

    public static void SetWeaponSprite(UISprite sprite, DItem item)
    {
        string modelName = TextController.GetItemDefine(item);

        SetWeaponSprite(sprite, modelName);
    }

    public static void SetWeaponSprite(UISprite sprite, int itemId)
    {
        string modelName = TextController.GetItemDefine(itemId);

        SetWeaponSprite(sprite, modelName);
    }

    public static void SetWeaponSprite(UISprite sprite, string modelName)
    {
        string ModelClass = MyUtil.FindWeaponClassWithItemDef(modelName);

        int max = (int)WeaponAtlas.max;
        int weaponIndex = 0;  //기타등등은 0
        for (int i = 1; i < max ; i++)  // 1번부터 검사
        {
            if ((((WeaponAtlas)i).ToString()).Contains(ModelClass))
            {
                weaponIndex = i;
                break;
            }
        }

        sprite.atlas = Instance.m_AtlasContainer[weaponIndex].atlas;
        sprite.spriteName = modelName;
    }
}
